import { Message, MessageBox } from 'element-ui'
import { Notification } from 'element-ui';
import { Loading } from 'element-ui';
import tokenUtil from "@/core/util/tokenUtil.js";
import { mapGetters } from "vuex";
import apiUtil from "@/core/util/apiUtil.js";
import { ROUTER_STORE, getRoutes } from "@/store/router.module";
import exp from 'constants';
import { async } from 'q';

/**
 * 设置Cookie
 * @param {} cName
 * @param {} value
 */
export function setCookie(cName, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie =
    cName +
    "=" +
    escape(value) +
    (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}

/**
 * 获取Cookie
 * @param {} Name
 * @return {}
 */
export function getCookie(Name) {
  var search = Name + "=";
  if (window.parent.document.cookie.length > 0) {
    var offset = window.parent.document.cookie.indexOf(search);
    if (offset != -1) {
      offset += search.length;
      var end = window.parent.document.cookie.indexOf(";", offset);
      if (end == -1) end = window.parent.document.cookie.length;
      return unescape(window.parent.document.cookie.substring(offset, end));
    } else return "";
  }
}

/**
 * 删除Cookie
 * @param {} name
 */
export function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null)
    window.parent.document.cookie =
      name + "=" + cval + ";expires=" + exp.toGMTString();
}

/**
 * 从缓存中清除Cookie
 * @param {} name
 */
export function clearCookie(name) {
  var expdate = new Date();
  expdate.setTime(expdate.getTime() - 86400 * 1000 * 1);
  setCookie(name, "", expdate);
}

/**
 * form data转json
 * @param {*} formData 
 * @returns 
 */
export function formDataToJson(formData) {
  var objData = {};
  formData.forEach(function (curValue, index, arr) {
    objData[index] = curValue;
  });
  return JSON.stringify(objData)
}

/**
 * 
 * @param {显示笼罩层} wsetting 
 * @returns 
 */
let globalLoading;
let globalLoadingRequestCount = 0;//当前正在请求的数量
export function showWating(wsetting) {
  if (globalLoadingRequestCount === 0 && !globalLoading) {
    if (wsetting && wsetting.renderBody) {
      // 显示加载进度条
      globalLoading = Loading.service({
        lock: true,//lock的修改符--默认是false
        text: wsetting && wsetting.message ? wsetting.message : "拼命加载中...",//显示在加载图标下方的加载文案
        // spinner: 'el-icon-loading',//自定义加载图标类名
        spinner: 'spinner-border text-primary',//自定义加载图标类名
        background: wsetting && wsetting.background ? wsetting.background : 'rgba(0, 0, 0, 0.6)',//遮罩层颜色
        // body:wsetting && wsetting.body?wsetting.body:true,
        target: document.querySelector('#' + wsetting.renderBody)//loadin覆盖的dom元素节点
      });
    } else {
      // 显示加载进度条
      globalLoading = Loading.service({
        lock: true,//lock的修改符--默认是false
        text: wsetting && wsetting.message ? wsetting.message : "拼命加载中...",//显示在加载图标下方的加载文案
        // spinner: 'el-icon-loading',//自定义加载图标类名
        spinner: 'spinner-border text-primary',//自定义加载图标类名
        background: wsetting && wsetting.background ? wsetting.background : 'rgba(0, 0, 0, 0.6)',//遮罩层颜色、
        target: "body"
      });
    }
  }
  globalLoadingRequestCount++;
}

/**
 * 关闭笼罩层
 * @param {*} wsetting 
 */
export function closeWating(wsetting) {
  globalLoadingRequestCount--;
  globalLoadingRequestCount = Math.max(globalLoadingRequestCount, 0); //做个保护
  if (globalLoadingRequestCount === 0) {
    //关闭loading
    toHideLoading();
  }
}

/**
 * 防抖动设置300ms间隔内的关闭进度条便合并为一次。
 * 防止连续请求时， loading闪烁的问题。
 */
var toHideLoading = _.debounce(() => {
  if (null != globalLoading) {
    globalLoading.close();
    globalLoading = null;
  }
}, 300);

/**
 * 封装 element-ui弹框
 * @param text
 * @param type
 * @returns {Promise}
 */
export function handleConfirm(text = "确定执行此操作吗？", type = "danger") {
  return MessageBox.confirm(text, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: type
  });
}

/**
 * 封装element-ui消息提示
 * @param text
 * @param type
 * @returns {Promise}
 */
export function handleAlert(text = "操作成功", type = "success", duration = 3) {
  return Message({
    showClose: true,
    message: text,
    center: true,
    type: type,
    duration: duration * 1000
  });
}

/**
 * 封装Notify提示组件
 * @param title
 * @param message
 * @param type
 * @returns {*}
 */
export function handleNotify(title = '标题', message = '内容', type = '类型', position = 'top-right', time = '3000') {
  Notification({
    title: title,
    message: message,
    type: type,         // success,warning,info,error
    position: position, // bottom-right/left,top-right/left
    duration: time      // 0不自动关闭
  })
}

/**
 * 深度拷贝
 * @param {*} data 
 * @returns 
 */
export const deepClone = (data) => {
  let result
  if (typeof data === 'object') {
    if (data == null) {
      result = null
    } else {
      if (data.constructor === Array) {
        result = []
        for (const i in data) {
          result.push(deepClone(data[i]))
        }
      } else {
        result = {}
        for (const i in data) {
          result[i] = deepClone(data[i])
        }
      }
    }
  } else {
    result = data
  }
  return result
}

/* 
将数组分割成多个数组
arr:要分割的数组
size : 分割后每个数组的长度
*/
export function chunkArray(arr, size) {
  let changeIndex = 0;
  let secondArr = [];
  while (changeIndex < arr.length) {
    secondArr.push(arr.slice(changeIndex, changeIndex += size))
  }
  return secondArr;
}

/**
 *
 * @returns {*}
 */
export function createXHR() {
  //检查是否支持XMLHttpRequest
  if (typeof XMLHttpRequest != "undefined") {
    //支持，返回XMLHttpRequest对象
    return new XMLHttpRequest();
  } else if (typeof ActiveXObject != "undefined") {//若是不支持XMLHttpRequest，就检查是否支持ActiveXObject
    //检查activeXString
    if (typeof arguments.callee.activeXString != "string") {
      let versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len;
      for (i = 0, len = versions.length; i < len, i++;) {
        try {
          new ActiveXObject(versions[i]);
          arguments.callee.activeXString = versions[i];
          break;
        } catch (ex) {

        }
      }
    }
    return new ActiveXObject(arguments.callee.activeXString);//返回ActiveXObject
  } else {
    handleAlert("浏览器版本不支持下载！", "warning", 3);
    return null;
  }
}


/**
 *
 * @param url
 * @param method
 * @param fileName
 * @param params
 */
export function downloadFileCallFn(url, method, fileName, params) {
  let token = `${tokenUtil.getToken()}`;
  let xhr = createXHR();// 创建ajax异步对象
  console.log("xhr.status", xhr.status);

  if (null == xhr) {
    return;
  }
  xhr.timeout = 30000000;
  xhr.ontimeout = function (event) {
    handleAlert("请求超时", "warning", 3);
  }
  handleAlert("开始下载...", "info", 3);
  if (method.toLowerCase() == "post") {//POST
    xhr.open("POST", url, true);
    xhr.setRequestHeader("token", token);//设置header
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(params);// 发送请求
  } else {//GET
    xhr.open(method, url, true);
    xhr.setRequestHeader("token", token);//设置header
    xhr.send();// 发送请求
  }
  xhr.responseType = "blob"; // 设置响应类型为 blob形式
  let URL = window.URL || window.webkitURL;
  xhr.onreadystatechange = function (res) {// 响应
    if (xhr.readyState === 4) {
      if (xhr.status === 200) { // 响应成功
        let blobText = xhr.response; // 将返回的二进制流文件转换为blob形式的
        let a = document.createElement('a');// 创建a元素
        a.href = URL.createObjectURL(blobText); // 设置href,URL.createObjectURL(blobText) 将blob读取成一个url
        a.download = fileName; // 设置下载文件名称
        document.body.appendChild(a)
        a.click(); // 触发事件
        a.remove(); // 下载完成移除a元素
        handleAlert("下载完毕！", "success", 3);
      } else {
        handleAlert("下载失败！", "error", 3);// 响应失败处理
      }
    }
  };
}

/**
 * 时间对象的格式化;
 */
Date.prototype.format = function (format) {
  /*
   * eg:format="YYYY-MM-dd hh:mm:ss";
   */
  var o =
  {
    "M+": this.getMonth() + 1, // month
    "d+": this.getDate(), // day
    "h+": this.getHours(), // hour
    "m+": this.getMinutes(), // minute
    "s+": this.getSeconds(), // second
    "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
    "S": this.getMilliseconds() // millisecond
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
}

/**
 * 
 * @param {*} dataStr 
 * @returns 
 */
export function dateformat(dataStr) {
  if (null != dataStr) {
    let date = new Date(dataStr);
    return date.format("yyyy-MM-dd hh:mm:ss");
  }
  return "";
}


/**
 * 验证文件类型是图片还是非图片
 * @param {} type 
 */
export function isImageByType(type) {
  if ("image/jpeg" === type || "image/png" === type || "image/gif" === type || "image/bmp" === type) {
    return true;
  } else {
    return false;
  }
}

// /**
//  * 
//  * @param {*} src 
//  */
// export function getBimghw(src){
//   let imageAttribute = [];
//   try{     
//       let img_url = src+'?'+Date.parse(new Date());
//       //创建对象
//       let img = new Image();
//       //改变图片的src
//       img.src = img_url;
//       // 加载完成执行
//       let w =260;
//       let h =200;      

//       img.onload = function(){

//           w = img.width;
//           h = img.height;
//           if(h > 400){
//               h = 400;
//           }else{
//               h = 200;
//           }

//           if(w>1000){
//               w = 708;
//           }else{
//               w = 260;
//           }
//           imageAttribute.w = w;
//           imageAttribute.h = h; 
//           imageAttribute.url = img_url;
//           return imageAttribute;
//       };
//       img.onerror = function(){
//         handleAlert("该图片不能预览", "warning", 3)
//         return imageAttribute;
//       };
//   }catch(e){
//       //非法即不满足图片
//       handleAlert("该图片不能预览", "warning", 3);
//       return imageAttribute;
//   }
// }


/**
 * 递归方式处理父节点
 * @param {*} data 
 */
export function doRouterTree(data) {
  const parent = []
  for (let i = 0; i < data.length; i++) {
    if ("0" === data[i].parentId) {
      let assemblyUri = data[i].componentRouterTo;//目标地址或component组件地址
      const pRouter = {
        path: data[i].componentRouter,
        id: data[i].id,
        meta:{
          title: data[i].name,
          icon: data[i].componentIcon,
          canClose: true,
        },
        component: (resolve) => require(["@/view/layout/layout"], resolve),
      };
      if ('' !== assemblyUri && null !== assemblyUri) {
        pRouter.children = [{
          id: data[i].id,
          name: data[i].componentRouter,
          path: data[i].componentRouter,
          meta:{
            title: data[i].name,
            icon: data[i].componentIcon,
            canClose: true,
          },
          component: (resolve) => require(["@/view/" + assemblyUri.replace("/view/", "")], resolve),
        }];
      }
      parent.push(pRouter);
    }
  }
  doRouterChildrenTree(parent, data)//递归处理子菜单

  //解决刷新页面404
  let page404 = {
    path: "/404",
    name: "404",
    title:'404',
    component: () => import("@/view/sys/error/404.vue")
  }
  let router404 = {
    path: "*",
    redirect: "/404"
  }
  parent.push(page404);
  parent.push(router404);
  return parent;
}

/**
 * 处理子节点
 * @param {*} parent 
 * @param {*} data 
 */
export function doRouterChildrenTree(parent, data) {
  if (data && parent) {
    for (let i = 0; i < parent.length; i++) {
      for (let j = 0; j < data.length; j++) {
        if (parent[i].id === data[j].parentId) {
          let assemblyUri = data[j].componentRouterTo;
          if (null === assemblyUri || '' === assemblyUri) {
            let children = {
              id: data[j].id,
              name: data[j].componentRouter,
              path: data[j].componentRouter,
              meta:{
                title: data[j].name,
                canClose: true,
                icon: data[j].componentIcon,
              }
            };
            //注意： require(["@/view/"+assemblyUri 这种写法可以 千万不要写成require(["@"+assemblyUri 一个@符合是不行的
            children.component = (resolve) => require(["@/view/layout/layout"], resolve)
            if (undefined === parent[i].children) {
              parent[i].children = [];
            }
            parent[i].children.push(children)
          } else {
            let children = {
              id: data[j].id,
              name: data[j].componentRouter,
              path: data[j].componentRouter,
              meta:{
                title: data[j].name,
                canClose: true,
                icon: data[j].componentIcon,
              }
            };
            //注意： require(["@/view/"+assemblyUri 这种写法可以 千万不要写成require(["@"+assemblyUri 一个@符合是不行的
            children.component = (resolve) => require(["@/view/" + assemblyUri.replace("/view/", "")], resolve)
            if (undefined === parent[i].children) {
              parent[i].children = [];
            }
            parent[i].children.push(children)
          }
        }
      }
      doRouterChildrenTree(parent[i].children, data)
    }
  }
}

/**
 * 非递归方式只取一级
 * @param {*} dataMenuList 
 * @returns 
 */
export function doRouter(dataMenuList) {//处理动态路由
  const router = [];
  if (dataMenuList) {
    const pRouter = {
      path: "/",
      component: (resolve) => require(["@/view/layout/layout"], resolve),
      children: [],
    };
    for (let i in dataMenuList) {
      let data = dataMenuList[i];
      let assemblyUri = data.componentRouterTo;
      if (null != data.componentRouter && '' != data.componentRouter) {
        let children = {
          name: data.componentRouter,
          path: data.componentRouter,
          meta:{
            title: data.name,
            canClose: true,
            icon: data.componentIcon,
          }
        };
        //注意： require(["@/view/"+assemblyUri 这种写法可以 千万不要写成require(["@"+assemblyUri 一个@符合是不行的
        children.component = (resolve) => require(["@/view/" + assemblyUri.replace("/view/", "")], resolve)
        pRouter.children.push(children);
      }
    }
    router.push(pRouter);
  }
  //解决刷新页面404
  let page404 = {
    path: "/404",
    name: "404",
    meta:{
      title: "404",
      canClose: true,
    },
    component: () => import("@/view/sys/error/404.vue")
  }
  let router404 = {
    path: "*",
    redirect: "/404"
  }
  router.push(page404);
  router.push(router404);
  return router;
}

/**
 * 
 */
export function reloadRouter(isReq) {
  const JEHC_ROUTER = "Routers";
  return new Promise((resolve, reject) => {
    if(isReq === true){
      apiUtil.get(process.env.VUE_APP_OAUTH_API + "/init/v1").then(({ data }) => {
        let dataMenuList = [];
        if (null != data.data && null != data.data.menuEntity) {
          let result = data.data.menuEntity;       
          for (let i in result) {
            let arr = result[i];
            if (null != arr && "" != arr) {
              let menuArr = JSON.parse(arr.menuList);
              if (null != menuArr && menuArr.length > 0) {
                for (let j in menuArr) {
                  dataMenuList.push(menuArr[j]);
                }
              }
            }
          }
        }
        setLocalItem(JEHC_ROUTER, JSON.stringify(dataMenuList));
        let result = doRouter(dataMenuList);//非递归方式 只取一级
        // let result = doRouterTree(dataMenuList);//采用递归方式
        resolve(result)
      });
    }else{
      let result = doRouter();//非递归方式 只取一级
      resolve(result)
    }  
  })
}

/**
 * 编写动态路由组装业务逻辑方法
 */
export function getDynamicsRouters(isReq,isSetLoad) {
  const JEHC_ROUTER_NEED_LOAD = "JEHC_ROUTER_NEED_LOAD"; 
  return new Promise((resolve, reject) => {
    let localRoutersJson = localStorage.getItem("Routers");
    if (!localRoutersJson) {
      reloadRouter(isReq).then(res => {
        if (null != res && res.length > 0) {
          // console.log("重新请求...",res);        
          resolve(res)
          if(isReq && isSetLoad){
            setLocalItem(JEHC_ROUTER_NEED_LOAD, 1);//重新请求的时候 设置标识 用于 动态路由重新加载
          }
        }
      })
    } else {
      let localRouters = JSON.parse(localRoutersJson);
      // let localRoutersRes = doRouterTree(localRouters);      
      let localRoutersRes = doRouter(localRouters);
      if (null != localRoutersRes) {//从缓存中读取        
        // console.log("从缓存中加载路由...");
        resolve(localRoutersRes)
      }
    }
  })
}

/**
 * 设置缓存
 * @param {*} key 
 * @param {*} value 
 */
export function setLocalItem(key,value){
  window.localStorage.setItem(key, value);
}

/**
 * 删除缓存
 * @param {*} key 
 * @param {*} value 
 */
export function removeLocalItem(key){
  window.localStorage.removeItem(key);
}

/**
 * 获取缓存
 * @param {*} key 
 * @param {*} value 
 */
export function getLocalItem(key){
  return window.localStorage.getItem(key);
}

/**
 * 验证手机号码
 * @param {*} value 
 * @returns 
 */
export function checkPhoneNumber(value) {
  const reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
  if (!value) {
    handleAlert("请填写手机号码！", "error", 3);
    return false;
  } else if (!reg.test(value)) { 
    handleAlert("请填写正确的手机号码！", "error", 3);
    return false;
  }else{
    return true;
  }
}

/**
 * idCard身份证
 * @param {*} value 
 * @returns 
 */
export function checkIdCard( value) {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!value) {
    handleAlert("证件号码不能为空", "error", 3);
    return false;
  } else if (!reg.test(value)) {
    handleAlert("证件号码不正确", "error", 3);
    return false;
  } else {
    return true;
  }
}

/**
 * 根据idCard身份证获取生日
 * @param {*} value 
 * @returns 
 */
export function getBirthDayByIdCard( value) {
    // 出生日期验证
    var sBirthday = (
        value.substr(6, 4) +
        "-" +
        Number(value.substr(10, 2)) +
        "-" +
        Number(value.substr(12, 2))
    ).replace(/-/g, "-"),
    d = new Date(sBirthday);    
    if (sBirthday != d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()) {
      handleAlert("身份证号出生日期非法", "error", 3);
      return "";
    }
    return sBirthday;
}


/**
 * 根据idCard身份证获取性别
 * @param {*} value 
 * @returns 
 */
export function getGenderByIdCard( idCard) {
  let gender = null;
  let val = idCard.length;
  if(val===18){
    gender = idCard.substring(16,17);
  }
  if(val===15){
    gender = idCard.substring(13,14);
  }
  if(gender%2 === 0)
    gender = 1 //女
  else
    gender = 0 //男
  return gender;
}

/**
 * 通过身份证号计算年龄
 * @param {*} iden 
 * @returns 
 */
export function getAgeByIdCard(iden) {
  if(null == iden || '' == iden){
      return "";
  }
  let val = iden.length
  let myDate = new Date()
  let month = myDate.getMonth() + 1
  let day = myDate.getDate()
  let age = 0
 
  if (val === 18) {
    age = myDate.getFullYear() - iden.substring(6, 10) - 1
    if (
      iden.substring(10, 12) < month ||
      (iden.substring(10, 12) == month && iden.substring(12, 14) <= day)
    )
      age++
  }
  return age
}